package com.kaigejava.juc.concurrentcontainers;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * @author kaigejava
 * arrayList、Vactor、CopayOnWriteArrayList比较
 */
public class ArrayListVsVactorVsCopyOnWriteArrayListTest {
    public static void main(String[] args) {
        //使用线程不安全的arrayList
      //  List<String> arryList = new ArrayList<>();
        //使用vector
      //  List<String> arryList = new Vector<>();
        //使用copyOnWriteArrayList
        List<String> arryList = new CopyOnWriteArrayList<>();

        Random random = new Random();
        Thread [] threadArr = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threadArr.length);
        Long beginTime = System.currentTimeMillis();
        for(int i = 0;i<threadArr.length;i++){
            threadArr[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for(int j = 0; j < 1000; j++){
                        try {
                            arryList.add("value" + random.nextInt(100000));
                        } catch (Exception e) {

                        }
                    }
                    latch.countDown();
                }
            });
        }
        for(Thread t : threadArr){
            t.start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("执行copyOnWriteArrayList时间为 ： " + (endTime-beginTime) + "毫秒！");
        System.out.println("List.size() : " + arryList.size());
    }
}
